import * as qiniu from 'qiniu'
import { Injectable } from '@nestjs/common'
import * as APP_CONFIG from '@app/app.config'

export interface FileUploader {
  name: string
  file: string | Uint8Array | Buffer
  region: string
  bucket: string
}

export interface UploadResult {
  key: string
  url?: string
  eTag?: string
  size?: number
}

@Injectable()
export class QiNiuService {
  private createQNConfig() {
    return new qiniu.conf.Config({
      zone: qiniu.zone.Zone_z0,
      useHttpsDomain: APP_CONFIG.QINIU.use_https_domain,
      useCdnDomain: APP_CONFIG.QINIU.use_cdn_domain
    })
  }

  /** 生成凭证 */
  private createToken(bucket: string) {
    const mac = new qiniu.auth.digest.Mac(APP_CONFIG.QINIU.accessKey, APP_CONFIG.QINIU.secretKey)
    return new qiniu.rs.PutPolicy({
      scope: bucket,
    }).uploadToken(mac)
  }

  public uploadFile(payload: FileUploader): Promise<UploadResult> {
    const { bucket, name: key } = payload
    const formUploader = new qiniu.form_up.FormUploader(this.createQNConfig())
    const putExtra = new qiniu.form_up.PutExtra()
    const uploadToken = this.createToken(bucket)
    return new Promise((resolve, reject) => {
      formUploader.put(uploadToken, key, payload.file, putExtra, (respErr, respBody) => {
        if (respErr) {
          reject(respErr)
        }
        const result = {
          key,
          ...respBody,
        }
        resolve(result)
      })
    })
  }
}
